package com.webserver.core;

import com.webserver.http.WebServerRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run(){
        try {
            //分析请求
            WebServerRequest request = new WebServerRequest(socket);

            //处理请求
            String path = request.getUri();

            //发送响应
            File rootDir = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
            File staticDir = new File(rootDir,"static");
            File file = new File(staticDir,path);
            //1.状态行
            println("HTTP/1.1 200 OK");
            //2.响应头
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());
            println("");
            //3.响应正文
            FileInputStream fis = new FileInputStream(file);
            OutputStream out = socket.getOutputStream();
            byte[] data = new byte[1024*10];
            int len;
            while ((len = fis.read(data)) != -1){
                out.write(data,0,len);
            }


        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void println(String line) throws IOException {
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        OutputStream out = socket.getOutputStream();
        out.write(data);
        out.write(13);
        out.write(10);
    }
}
